package com.hoow.shakoow.shake

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.*
import android.provider.MediaStore
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.hoow.shakoow.R
import com.hoow.shakoow.ai.data.*
import com.hoow.shakoow.ai.enums.ProductEditEnum
import com.hoow.shakoow.ai.home.NetworkViewModel
import com.hoow.shakoow.base.BaseActivity
import com.hoow.shakoow.base.BaseActivityConnectionAction
import com.hoow.shakoow.components.dialog.ImagePickerDialog
import com.hoow.shakoow.components.dialog.MessageDialog
import com.hoow.shakoow.ai.data.ReqImageUpload
import com.hoow.shakoow.databinding.ActivityUserAblumSelfBinding
import com.hoow.shakoow.enums.PageTagEnum
import com.hoow.shakoow.extend.*
import com.hoow.shakoow.shake.adapter.UserAblumAdapter
import com.hoow.shakoow.shake.components.imageView.ShakeImageGallary
import com.hoow.shakoow.utils.analytics.util.AnalyticsUtil
import java.io.File


/** 相册列表页 */
@SuppressLint("CustomSplashScreen")
class UserAblumSelfActivity : BaseActivity(), BaseActivityConnectionAction {

    //布局binding
    private lateinit var mActivityBinding: ActivityUserAblumSelfBinding

    // 适配器
    private lateinit var mUserAblumAdapter: UserAblumAdapter

    // 调起相机
    private var mImageIntent: Intent? = null
    private var mImageCameraActivityResultLauncher: ActivityResultLauncher<Intent>? = null
    private var mImageFilePath = ""

    // 调起相册
    private var mImageAlbumActivityResultLauncher: ActivityResultLauncher<String>? = null

    // 是否全选
    private var mIsSelectAll = false

    //api接口viewModel
    private val mNetworkViewModel by lazy {
        ViewModelProvider(this)[NetworkViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mNetworkViewModel)
        return list
    }

    override fun onBindingViewTag(): String {
        return PageTagEnum.user_photos_self.name.uppercase()
    }

    override fun onBindingContentView(): View {
        mActivityBinding = ActivityUserAblumSelfBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("SetTextI18n", "SourceLockedOrientationActivity", "NotifyDataSetChanged")
    override fun onContentViewBinded() {
        try {
            //初始化拍照与选择图片回调
            registerTakePicActivityResultCallback()
            registerAlbumActivityResultCallback()

            // 上传图片返回
            mNetworkViewModel.onUploadFileLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        if (result.isNotBlank()) {
                            mNetworkViewModel.mImageUrl = result

                            // 保存相册
                            val photos = mutableListOf(result)
                            val reqUploadUserPhotos = ReqUploadUserPhotos(photoUrls = photos)
                            mNetworkViewModel.uploadUserPhotos(reqUploadUserPhotos)
                        }
                    }
                }
            }

            // 上传相册返回
            mNetworkViewModel.onUploadUserPhotosLiveData.observe(this) {
                // 获取用户相册
                mNetworkViewModel.getUserPhotos(ReqAiBase())
            }

            // 删除相册返回
            mNetworkViewModel.onDeleteUserPhotosLiveData.observe(this) {
                // 更新状态
                for (index in 1 until mNetworkViewModel.mUserAblumWithDeleteItemList.size) {
                    val item = mNetworkViewModel.mUserAblumWithDeleteItemList[index]
                    item.isEdit = false
                    item.isSelected = false
                }
                // 刷新列表
                mUserAblumAdapter.notifyDataSetChanged()

                // 隐藏底部操作栏
                mActivityBinding.llAblumEditActionBg.visibility = View.GONE

                // 获取用户相册
                mNetworkViewModel.getUserPhotos(ReqAiBase())
            }

            // 获取相册返回
            mNetworkViewModel.onGetUserPhotosLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        mNetworkViewModel.mUserAblumList.clear()
                        mNetworkViewModel.mUserAblumList.addAll(result)

                        mNetworkViewModel.mUserAblumWithDeleteItemList.clear()

                        // 增加删除项目
                        mNetworkViewModel.mUserAblumWithDeleteItemList.add(
                            RevObjUserAblum(id = "0", imgUrl = "")
                        )
                        mNetworkViewModel.mUserAblumWithDeleteItemList.addAll(result)

                        // 更新列表
                        mUserAblumAdapter.notifyDataSetChanged()

                        // 更新空白页展示
                        if (mNetworkViewModel.mUserAblumWithDeleteItemList.size > 0) {
                            mActivityBinding.emptyLayout.llEmptyList.visibility = View.GONE
                        } else {
                            mActivityBinding.emptyLayout.llEmptyList.visibility = View.VISIBLE
                        }
                    }
                }
            }

            // 初始化适配器
            UserAblumAdapter.initItemSize(this)
            mUserAblumAdapter =
                UserAblumAdapter(true, mNetworkViewModel.mUserAblumWithDeleteItemList)
            mUserAblumAdapter.setItemClickListener { position, avatarLink, action ->
                if (action == UserAblumAdapter.ACTION_CLICK) {
                    //点击图片
                    ShakeImageGallary.showDialog(
                        fragmentManager = supportFragmentManager,
                        dataList = mNetworkViewModel.mUserAblumList,
                        index = (position - 1)
                    )
                } else if (action == UserAblumAdapter.ACTION_ADD) {
                    // 去添加图片
                    // 去掉选中状态
                    mIsSelectAll = false
                    for (index in 1 until mNetworkViewModel.mUserAblumWithDeleteItemList.size) {
                        val item = mNetworkViewModel.mUserAblumWithDeleteItemList[index]
                        item.isEdit = false
                        item.isSelected = false
                    }
                    // 刷新列表
                    mUserAblumAdapter.notifyDataSetChanged()

                    // 隐藏底部操作栏
                    mActivityBinding.llAblumEditActionBg.visibility = View.GONE

                    // 两种，拍照与选择相册
                    ImagePickerDialog.showDialog(supportFragmentManager) { pickType ->
                        mNetworkViewModel.mImageAction = pickType
                        if (pickType == ImagePickerDialog.PICK_TYPE_ALBUM) {
                            openAblum()
                        } else if (pickType == ImagePickerDialog.PICK_TYPE_CAMER) {
                            requestExtPermissoins()
                        }
                    }
                } else if (action == UserAblumAdapter.ACTION_DELETE_SELECTED) {
                    // 删除选中
                    if (mNetworkViewModel.mUserAblumWithDeleteItemList.size > position) {
                        // 更新状态
                        val item = mNetworkViewModel.mUserAblumWithDeleteItemList[position]
                        item.isEdit = true
                        item.isSelected = !item.isSelected

                        // 刷新列表
                        mUserAblumAdapter.notifyDataSetChanged()
                    }
                }
            }

            mActivityBinding.rcAblumList.layoutManager =
                StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL)
            mActivityBinding.rcAblumList.adapter = mUserAblumAdapter

            // 点击编辑
            mActivityBinding.topNavBarInfo.setOnActionClickListener { action ->
                if (action == R.integer.NavbarActionRight) {
                    if (mNetworkViewModel.mUserAblumWithDeleteItemList.size > 1) {
                        if (mActivityBinding.llAblumEditActionBg.visibility == View.VISIBLE) {
                            for (index in 1 until mNetworkViewModel.mUserAblumWithDeleteItemList.size) {
                                val item = mNetworkViewModel.mUserAblumWithDeleteItemList[index]
                                item.isEdit = false
                                item.isSelected = false
                            }
                            // 刷新列表
                            mUserAblumAdapter.notifyDataSetChanged()

                            //隐藏底部操作栏
                            mActivityBinding.llAblumEditActionBg.visibility = View.GONE

                        } else {
                            for (index in 1 until mNetworkViewModel.mUserAblumWithDeleteItemList.size) {
                                val item = mNetworkViewModel.mUserAblumWithDeleteItemList[index]
                                item.isEdit = true
                            }
                            // 刷新列表
                            mUserAblumAdapter.notifyDataSetChanged()

                            //显示底部操作栏
                            mActivityBinding.llAblumEditActionBg.visibility = View.VISIBLE
                        }
                    }

                    // 打点：摇一摇
                    AnalyticsUtil.saveHitPointInfo(
                        type = "ABLUM_EDIT_CLICK",
                        remark = ""
                    )
                }
            }

            // 点击全选
            mActivityBinding.llAblumEditActionSelectAllBg.setOnClickListener {
                // 更新状态
                mIsSelectAll = !mIsSelectAll
                for (index in 1 until mNetworkViewModel.mUserAblumWithDeleteItemList.size) {
                    val item = mNetworkViewModel.mUserAblumWithDeleteItemList[index]
                    item.isEdit = true
                    item.isSelected = mIsSelectAll
                }

                // 刷新列表
                mUserAblumAdapter.notifyDataSetChanged()

                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "ABLUM_SELECT_ALL",
                    remark = ""
                )
            }
            mActivityBinding.imageAblumEditActionSelectAll.setOnClickListener {
                // 更新状态
                mIsSelectAll = !mIsSelectAll
                for (index in 1 until mNetworkViewModel.mUserAblumWithDeleteItemList.size) {
                    val item = mNetworkViewModel.mUserAblumWithDeleteItemList[index]
                    item.isEdit = true
                    item.isSelected = mIsSelectAll
                }

                // 刷新列表
                mUserAblumAdapter.notifyDataSetChanged()
            }

            // 点击删除
            mActivityBinding.llAblumEditActionDeleteBg.setOnClickListener {
                val list = mutableListOf<String>()
                for (index in 1 until mNetworkViewModel.mUserAblumWithDeleteItemList.size) {
                    val item = mNetworkViewModel.mUserAblumWithDeleteItemList[index]
                    if (item.isEdit and item.isSelected) {
                        list.add(item.id)
                    }
                }

                if (list.isNotEmpty()) {
                    // 删除相册
                    mNetworkViewModel.deleteUserPhotos(ReqDeleteUserPhotos(ids = list))
                } else {
                    Toast.makeText(
                        this,
                        getString(R.string.shake_pls_select_pic_first),
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
            mActivityBinding.imageAblumEditActionDelete.setOnClickListener {
                val list = mutableListOf<String>()
                for (index in 1 until mNetworkViewModel.mUserAblumWithDeleteItemList.size) {
                    val item = mNetworkViewModel.mUserAblumWithDeleteItemList[index]
                    if (item.isEdit and item.isSelected) {
                        list.add(item.id)
                    }
                }

                if (list.isNotEmpty()) {
                    // 删除相册
                    mNetworkViewModel.deleteUserPhotos(ReqDeleteUserPhotos(ids = list))
                } else {
                    Toast.makeText(
                        this,
                        getString(R.string.shake_pls_select_pic_first),
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            // 获取用户相册
            mNetworkViewModel.getUserPhotos(ReqAiBase())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onPermissionsRequestAllPass() {
        //调起相机
        mImageCameraActivityResultLauncher?.launch(mImageIntent)
    }

    override fun takePicture() {
        //调起相机前，申请权限
        requestExtPermissoins()
    }

    override fun openAblum() {
        //调起相册
        mImageAlbumActivityResultLauncher?.launch("image/*")
    }

    /** 注册拍照回调 */
    @SuppressLint("Recycle", "Range")
    private fun registerTakePicActivityResultCallback() {
        try {
            //front
            mImageFilePath =
                getCacheImageFilePath("icfront")
            val imageFile = File(mImageFilePath)
            val imageUri: Uri = if (Build.VERSION.SDK_INT < 24) {
                Uri.fromFile(imageFile)
            } else {
                FileProvider.getUriForFile(this, "$packageName.file_provider", imageFile)
            }
            mImageIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                .apply { putExtra(MediaStore.EXTRA_OUTPUT, imageUri) }
            mImageCameraActivityResultLauncher =
                registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                    try {
                        pickResultFromCameraActivity(
                            outFilePath = mImageFilePath,
                            result = result,
                            convertFinish = { covetPath, bitmap ->
                                onHandlerImagePickResult(
                                    covetPath = covetPath,
                                    bitmap = bitmap
                                )
                            })
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /** 注册相册回调 */
    private fun registerAlbumActivityResultCallback() {
        try {
            mImageAlbumActivityResultLauncher =
                registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
                    try {
                        try {
                            pickResultFromAlbumActivity(
                                result = uri,
                                convertFinish = { covetPath, bitmap ->
                                    onHandlerImagePickResult(
                                        covetPath = covetPath,
                                        bitmap = bitmap
                                    )
                                })
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /** 处理选择/拍照回调 */
    private fun onHandlerImagePickResult(
        covetPath: String?,
        bitmap: Bitmap?
    ) {
        var validPath = false
        covetPath?.let {
            mNetworkViewModel.mImagePath = it
            validPath = true
        }

        var validBitmap = false
        bitmap?.let {
            mNetworkViewModel.mImageBitmap = it
            validBitmap = true
        }

        if (validPath and validBitmap) {
            //上传图片
            mNetworkViewModel.uploadFile(
                ReqImageUpload(
                    filePath = mNetworkViewModel.mImagePath,
                    cardType = ProductEditEnum.IMAGE_TO_IMAGE.name
                )
            )
        } else {
            MessageDialog.showDialog(
                fragmentManager = supportFragmentManager,
                message = getString(R.string.ai_please_upload_image_first),
            )
        }
    }

    /** 请求相机权限 */
    private fun requestExtPermissoins() {
        requestSpecPermissions(arrayOf(android.Manifest.permission.CAMERA))
    }
}